//
//  ImageAddition.m
//  EasyMI_iPhone
//
//  Created by chen wenhao on 13-1-10.
//
//

#import "ImageAddition.h"
#import <CoreGraphics/CoreGraphics.h>

@implementation ImageAddition

static void addRoundedRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight)
{
    float fw, fh;
    if (ovalWidth == 0 || ovalHeight == 0) {
        CGContextAddRect(context, rect);
        return;
    }
    CGContextSaveGState(context);
    CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGContextScaleCTM (context, ovalWidth, ovalHeight);
    fw = CGRectGetWidth (rect) / ovalWidth;
    fh = CGRectGetHeight (rect) / ovalHeight;
    CGContextMoveToPoint(context, fw, fh/2);
    CGContextAddArcToPoint(context, fw, fh, fw/2, fh, 1);
    CGContextAddArcToPoint(context, 0, fh, 0, fh/2, 1);
    CGContextAddArcToPoint(context, 0, 0, fw/2, 0, 1);
    CGContextAddArcToPoint(context, fw, 0, fw, fh/2, 1);
    CGContextClosePath(context);
    CGContextRestoreGState(context);
}

static void addChatRectToPath(CGContextRef context, CGRect rect, float ovalWidth, float ovalHeight,PointDirection direction)
{
    float fw, fh;
    if (ovalWidth == 0 || ovalHeight == 0) {
        CGContextAddRect(context, rect);
        return;
    }
    
    CGContextSaveGState(context);
    CGContextTranslateCTM (context, CGRectGetMinX(rect), CGRectGetMinY(rect));
    CGContextScaleCTM (context, ovalWidth, ovalHeight);
    fw = CGRectGetWidth (rect) / ovalWidth;
    fh = CGRectGetHeight (rect) / ovalHeight;
    
    float triangleY = fh-2.8;
    
    float triangleH = 1;

    if (direction==PointDirectionLeft) {
        
        CGFloat minx = 1, midx = fw/2.0+0.5, maxx = fw;
        CGFloat miny = 0, midy = fh/2.0, maxy = fh;
        
        //       minx    midx    maxx
        // miny    2       3       4
        // midy   1 9              5
        // maxy    8       7       6
        
        // Start at 1
        CGContextMoveToPoint(context, minx, midy);
        // Add an arc through 2 to 3
        CGContextAddArcToPoint(context, minx, miny, midx, miny, 1);
        // Add an arc through 4 to 5
        CGContextAddArcToPoint(context, maxx, miny, maxx, midy, 1);
        // Add an arc through 6 to 7
        CGContextAddArcToPoint(context, maxx, maxy, midx, maxy, 1);
        // Add an arc through 8 to 9
        CGContextAddArcToPoint(context, minx, maxy, minx, midy, 1);
        
        CGContextAddLineToPoint(context,minx,triangleY);

        CGContextAddLineToPoint(context,0,triangleY+triangleH/2.0);
        
        CGContextAddLineToPoint(context,minx,triangleY+triangleH);
        
        
    }else {
        
        CGFloat minx = 0, midx = fw/2.0-0.5, maxx = fw-1;
        CGFloat miny = 0, midy = fh/2.0, maxy = fh;
        
        //       minx    midx    maxx
        // miny    2       3       4
        // midy   1 9              5
        // maxy    8       7       6
        
        // Start at 5
        CGContextMoveToPoint(context, maxx, midy);
        // Add an arc through 4 to 3
        CGContextAddArcToPoint(context, maxx, miny, midx, miny, 1);
        // Add an arc through 2 to 1
        CGContextAddArcToPoint(context, minx, miny, minx, midy, 1);
        // Add an arc through 8 to 7
        CGContextAddArcToPoint(context, minx, maxy, midx, maxy, 1);
        // Add an arc through 6 to 5
        CGContextAddArcToPoint(context, maxx, maxy, maxx, midy, 1);
        
        CGContextAddLineToPoint(context,maxx,triangleY);
        
        CGContextAddLineToPoint(context,fw,triangleY+triangleH/2.0);
        
        CGContextAddLineToPoint(context,maxx,triangleY+triangleH);
        
    }
    
    CGContextClosePath(context);
    CGContextRestoreGState(context);
}


+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
    if (image==nil) {
        return nil;
    }
    UIGraphicsBeginImageContext(CGSizeMake(newSize.width*[UIScreen mainScreen].scale, newSize.height*[UIScreen mainScreen].scale));
    
    [image drawInRect:CGRectMake(0, 0, newSize.width*[UIScreen mainScreen].scale, newSize.height*[UIScreen mainScreen].scale)];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

+ (NSString *)imageFormat:(NSData *)data
{
    if (data.length >4) {
        const unsigned char * bytes = [data bytes];
        if (bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff)
        {
            NSLog(@"jpg");
            return @"jpg";
        }
        if (bytes[0] == 0x89 && bytes[1] == 0x50 && bytes[2] == 0x4e && bytes[3] == 0x47)
        {
            NSLog(@"png");
            return @"png";
        }
    }
    return nil;
}


+ (UIImage*)makeRoundCornerImage:(UIImage*)img rate:(float)rate
{
    UIImage * newImage = nil;
    if( nil != img)
    {
        float w = img.size.width;
        float h = img.size.height;
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace,kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault);
        CGColorSpaceRelease(colorSpace);
        CGContextBeginPath(context);
        CGRect rect = CGRectMake(0, 0, w, h);
        addRoundedRectToPath(context, rect, rate*w, rate*h);
        CGContextClosePath(context);
        CGContextClip(context);
        CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
        CGImageRef imageMasked = CGBitmapContextCreateImage(context);
        CGContextRelease(context);
        newImage = [UIImage imageWithCGImage:imageMasked];
        
        CGImageRelease(imageMasked);
    }
    return newImage;
}

+ (UIImage*)makeChatImage:(UIImage*)img rate:(float)rate direction:(PointDirection)direction
{
    UIImage * newImage = nil;
    if( nil != img)
    {
        float w = img.size.width;
        float h = img.size.height;
        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace,kCGImageAlphaPremultipliedLast | kCGBitmapByteOrderDefault);
        CGColorSpaceRelease(colorSpace);
        CGContextBeginPath(context);
        CGRect rect = CGRectMake(0, 0, w, h);
        addChatRectToPath(context, rect, rate*w, rate*h,direction);
        
        CGContextClosePath(context);
        CGContextClip(context);
        CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
        CGImageRef imageMasked = CGBitmapContextCreateImage(context);
        CGContextRelease(context);
        newImage = [UIImage imageWithCGImage:imageMasked];
        
        CGImageRelease(imageMasked);
    }
    return newImage;
}

+ (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage originalMaxWidth:(float)originalMaxWidth{
    float maxWidth = originalMaxWidth/sourceImage.scale;
    if (sourceImage.size.width < maxWidth) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = maxWidth;
        btWidth = sourceImage.size.width * (maxWidth / sourceImage.size.height);
    } else {
        btWidth = maxWidth;
        btHeight = sourceImage.size.height * (maxWidth / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth*sourceImage.scale, btHeight*sourceImage.scale);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

+ (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil) NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

+ (NSData *)thumbImage:(NSData *)data origin:(UIImage *)origin compressionQuality:(float)compressionQuality size:(float)size
{
    UIImage *image = nil;
    if (origin) {
        image = origin;
    }else {
        if ([data length]>0) {
            image = [UIImage imageWithData:data];
        }
    }
    
    if (image) {
        
        image = [ImageAddition imageByScalingToMaxSize:image originalMaxWidth:size];

        NSData *thumbData = UIImageJPEGRepresentation(image,compressionQuality);
        
        return thumbData;
    }
    
    return nil;
}

+ (NSString *)thumbPath:(NSString *)path
{
    NSString *thumbPath = [NSString stringWithFormat:@"%@_thumb",path];
    return thumbPath;
}

+ (UIImage *)thumbImage:(NSString *)path
{
    NSString *thumbIconPath = [NSString stringWithFormat:@"%@_thumb",path];
    UIImage *origin = [UIImage imageWithContentsOfFile:thumbIconPath];
    return origin;
}

+ (NSString *)originalPathAccordingToThumbPath:(NSString *)thumbPath
{
    NSString *originalPath =  [thumbPath stringByReplacingOccurrencesOfString:@"_thumb" withString:@""];
    return originalPath;
}
@end
